/*
 * @lc app=leetcode.cn id=224 lang=javascript
 *
 * [224] 基本计算器
 */

// @lc code=start
/**
 * @param {string} s
 * @return {number}
 */
var calculate = function (s) {
  const stack = [];
  let sign = 1;
  let num = 0;
  let result = 0;

  for (let c of s) {
    if (/\d/.test(c)) {
      num = num * 10 + Number(c);
    } else if (c === '+' || c === '-') {
      result += num * sign;
      num = 0;
      sign = c === '+' ? 1 : -1;
    } else if (c === '(') {
      stack.push(result);
      stack.push(sign);
      result = 0;
      sign = 1;
    } else if (c === ')') {
      result += num * sign;
      result *= stack.pop();
      result += stack.pop();
      num = 0;
    }
  }
  // 最后处理结尾不是括号的内容
  result += num * sign;

  return result;
};
// @lc code=end
